package sample;

import javafx.scene.control.TextArea;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

public class NewSPN extends Process implements Runnable{

	public NewSPN(ArrayList<PCB> PCBList, TextArea textArea) {
		super(PCBList, textArea);
	}

	public NewSPN() {
	}

	@Override
	public void run() {
		ArrayList<PCB> PCBList=super.getPCBList();
		//先根据时间排序
		super.setPCBList(quickSort(PCBList,0,PCBList.size()-1));
		for (int i = 0; i < super.getPCBList().size(); i++) {
			for (int j = PCBList.get(i).getTime(); j >= 0; ) {
				PCBList.get(i).setTime(j--);
				if (j <= 0) {
					PCBList.get(i).setStatus(-1);
				}
				for (int k = i; k < PCBList.size(); k++) {
					super.getTextArea().appendText(PCBList.get(k).print_pcb());
				}
				super.getTextArea().appendText("-------------------------------------------------------------------------------------------\n");
			}
		}
	}

	private ArrayList<PCB> quickSort(ArrayList<PCB> a, int low, int high) {
		int i=low;
		int j=high;
		int pivot = a.get(low).getTime();
		PCB temp;
		while (i < j) {
			while (i < j && a.get(j).getTime() > pivot) {//找第一个比pivot小的
				j--;
			}
			while (i < j && a.get(i).getTime() < pivot) {
				i++;
			}
			if (i < j) {
				temp = a.get(i);
				a.set(i,a.get(j));
				a.set(j,temp);
			}
		}
		if (i > low) {
			quickSort(a, low, i);
		}
		if (i < high ) {
			quickSort(a, i + 1, high);
		}
		return a;
	}

}
